<template>
  <div v-show="$route.name == 'task-update'">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/task-list' }">任务管理记录</el-breadcrumb-item>
      <el-breadcrumb-item>任务编辑</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-form :model="task" :rules="rules" ref="task" label-width="120px" class="demo-saveForm">
        <div class="title-name">任务编辑</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="项目" prop="project_id">
              <el-select v-model="task.project_id" popper-class="dropdownbox" class="form-item" placeholder="请选择项目" :disabled="auths.indexOf('change-connect-project') !== -1 ? false: true">
                <el-option v-for="item in projectList" :label="item.project_name"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.project_name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务名称" prop="task_name">
              <el-input v-model="task.task_name" placeholder="请输入任务名称" class="form-item" :disabled="auths.indexOf('change-connect-project') !== -1 ? false: true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="task_user_id">
              <el-select v-model="task.task_user_id" popper-class="dropdownbox" class="form-item" placeholder="请选择负责人" :disabled="auths.indexOf('change-connect-project') !== -1 ? false: true">
                <el-option v-for="item in userList" :label="item.truename"
                  :value="item.id" :key="item.id">
                  <span style="float: left">{{ item.truename }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开发状态" prop="dev_status">
              <el-radio-group v-model="task.dev_status" :disabled="auths.indexOf('dev-all-status') !== -1 || (userId * 1 === task.task_user_id && auths.indexOf('dev-status') !== -1) ? false: true">
                <el-radio :label="1">未开始</el-radio>
                <el-radio :label="2">开发中</el-radio>
                <el-radio :label="3">暂缓</el-radio>
                <el-radio :label="4">已完成</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需要检查" prop="is_check">
              <el-radio-group v-model="task.is_check" :disabled="auths.indexOf('choose-checkable') !== -1 ? false: true">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="task.is_check && task.check_status !== 0 && oldCheck !== 2">
            <el-form-item label="检查状态" prop="check_status">
              <el-radio-group v-model="task.check_status" :disabled="auths.indexOf('check-status') !== -1 ? false: true">
                <el-radio :label="1">待检查</el-radio>
                <el-radio :label="2">已驳回</el-radio>
                <el-radio :label="3">已通过</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预计完成时间" prop="estimated_date">
              <el-date-picker type="date" placeholder="选择日期" v-model="task.estimated_date" class="form-item" :disabled="auths.indexOf('change-connect-project') !== -1 ? false: true"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="任务描述" prop="desc">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 7 }" v-model="task.desc" class="form-item" :disabled="auths.indexOf('change-connect-project') !== -1 ? false: true"  style="width: 600px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="任务文件：" prop="fileList">
              <el-upload
                action="https://if.prowealthgroup.cn/task-produce/public/index.php/task-upload"
                list-type="picture-card"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="beforeRemove"
                :disabled = "auths.indexOf('change-connect-project') !== -1 ? false: true"
                :file-list="task.fileList">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left"></el-divider>
        <div class="title-name">添加日志</div>
        <el-row>
          <el-col :span="16">
            <el-form-item label="日志内容">
              <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 7}" v-model="editLog.text" class="form-item"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="日志图片：">
              <el-upload
                action="https://if.prowealthgroup.cn/task-produce/public/index.php/task-upload"
                list-type="picture-card"
                :on-preview="handlePreview"
                :on-remove="logRemove"
                :on-success="logSuccess"
                :on-error="handleError"
                :before-remove="beforeRemove"
                :file-list="editLog.picture">
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <el-row>
          <el-col :span="24">
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button  @click="back" style="margin-left: 5px">返回</el-button>
          </el-col>
        </el-row>
        <el-divider content-position="left"></el-divider>
        <div class="title-name">历史日志</div>
        <el-row>
          <el-timeline :reverse="true">
            <el-timeline-item :timestamp="item.insert_time" v-for="item in task.logList" :key="item.id">
              <div style="padding: 10px;">
                <p style="font-weight: bold;margin: 0;font-size: 16px;">{{item.truename}}</p>
                <p>{{item.note}}</p>
                <div class="demo-image__preview">
                  <el-image
                    :src="itemI.url"
                    :preview-src-list="item.paths"
                    v-for="itemI in item.images"
                    :key="itemI.url"
                    style="width: 120px; height: 120px; margin-right: 10px;">
                  </el-image>
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-row>
     </el-form>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      id: '',
      userId: '',
      auths: [],
      loading: false,
      projectList: [],
      task: {},
      userList: [],
      oldDev: '',
      oldCheck: '',
      rules: {
        dev_status: [{ required: true, message: '请选择开发状态', trigger: 'change' }],
        project_id: [{ required: true, message: '请选择项目', trigger: 'change' }],
        is_check: [{ required: true, message: '请选择是否检查', trigger: 'change' }],
        check_status: [{ required: true, message: '请选择检查状态', trigger: 'change' }],
        task_name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        task_user_id: [{ required: true, message: '请选择执行人', trigger: 'change' }],
        estimated_date: [{ required: true, message: '请选择日期', trigger: 'blur' }]
      },
      dialogImageUrl: '',
      dialogVisible: false,
      editLog: {
        text: '',
        picture: []
      },
      devAble: true,
      checkAble: true
    }
  },
  mounted() {
    this.getTaskData()
    this.getProject()
    this.getUserInfo()
  },
  watch: {
    'task.project_id': {
      handler: function(val, oldval) {
        if (val && oldval) {
          this.task.task_user_id = ''
        }
        this.getDevUserList()
      }
    },
    'task.is_check': {
      handler: function(val, oldval) {
        if (val === 0 && oldval > -1) {
          this.task.check_status = 0
        } else if (val && this.task.dev_status === 4 && oldval > -1) {
          this.task.check_status = 1
        }
      }
    },
    'task.check_status': {
      handler: function(val, oldval) {
        // 数据有变 且 测试状态主动变化
        // if (oldval > -1 && this.checkAble) {
        //   // 检查状态不变
        //   if (val === this.oldCheck && this.task.dev_status !== this.oldDev) {
        //     this.devAble = false // 开发状态被动变化
        //     this.task.dev_status = this.oldDev
        //   // 检查状态修改为已驳回
        //   } else if (val === 2 && this.task.dev_status !== 2) {
        //     this.devAble = false // 开发状态被动变化
        //     this.task.dev_status = 2
        //   // 检查状态修改为已通过
        //   } else if (val === 3 && this.task.dev_status !== 4) {
        //     this.devAble = false // 开发状态被动变化
        //     this.task.dev_status = 4
        //   } else if (this.task.dev_status !== this.oldDev) {
        //     this.devAble = false // 开发状态被动变化
        //     this.task.dev_status = this.oldDev
        //   }
        // 测试状态被动变化（改为主动）
        // } else if (!this.checkAble) {
        //   this.checkAble = true
        // }
        // 数据有变 且 测试状态主动变化
        if (oldval > -1 && this.checkAble) {
          // 若检查状态不变
          if (val === this.oldCheck && this.task.dev_status !== this.oldDev) {
            this.devAble = false // 开发状态被动变化
            this.task.dev_status = this.oldDev
          // 检查状态修改为已驳回
          } else if (val === 2 && this.task.dev_status !== 2) {
            this.devAble = false // 开发状态被动变化
            this.task.dev_status = 2
          // 检查状态修改为已通过
          } else if (this.task.dev_status !== 4 && this.task.is_check) {
            this.devAble = false // 开发状态被动变化
            this.task.dev_status = 4
          }
        // 测试状态被动变化（改为主动）
        } else if (!this.checkAble) {
          this.checkAble = true
        }
      }
    },
    'task.dev_status': {
      handler: function(val, oldval) {
        // 数据有变 且 是开发状态主动变化
        // if (oldval > -1 && this.devAble) {
        //   // 开发状态不变
        //   if (val === this.oldDev && this.task.check_status !== this.oldCheck) {
        //     this.checkAble = false // 测试状态被动变化
        //     this.task.check_status = this.oldCheck
        //   // 开发状态修改 开发中/未开始/暂缓/已完成
        //   } else if (this.task.check_status !== 0) {
        //     this.checkAble = false // 测试状态被动变化
        //     this.task.check_status = 0
        //   }
        // }
        // 开发状态被动变化（改为主动）
        // else if (!this.devAble) {
        //   this.devAble = true
        // }

        // 数据有变 且 是开发状态主动变化
        if (oldval > -1 && this.devAble) {
          // 若开发状态不变
          if (val === this.oldDev && this.task.check_status !== this.oldCheck) {
            this.checkAble = false // 测试状态被动变化
            this.task.check_status = this.oldCheck
          // 若开发状态改为完成 检查状态改为待检查
          } else if (val === 4 && this.task.check_status !== 1 && this.task.is_check) {
            this.checkAble = false // 测试状态被动变化
            this.task.check_status = 1
          // 其余 检查状态改为0
          } else if (this.task.check_status !== 0) {
            this.checkAble = false // 测试状态被动变化
            this.task.check_status = 0
          }
        // 开发状态被动变化（改为主动）
        } else if (!this.devAble) {
          this.devAble = true
        }
      }
    }
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      this.auths = JSON.parse(localStorage.task_auths)
      this.userId = localStorage.task_user
    },
    // 获取开发人员
    async getDevUserList() {
      this.userList = []
      const params = {
        page: 1,
        pageSize: 100000,
        project_id: this.task.project_id
      }
      const { data: result } = await this.$http.get('/user', { params: params })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      result.data.forEach(item => {
        if (item.auths.indexOf("task-publish-able") !== -1) {
          this.userList.push(item) 
        }
      })
    },
    // 获取任务
    async getTaskData() {
      if (this.$route.params.id) {
        this.id = this.$route.params.id
        localStorage.setItem('taskId', this.$route.params.id)
      } else {
        this.id = localStorage.getItem('taskId')
      }
      if (this.id) {
        this.getTask(this.id)
      }
    },
    // 获取项目
    async getProject() {
      const params = {
        page: 1,
        pageSize: 100000
      }
      const { data: result } = await this.$http.get('/project', { params: params })
      if (result.status !== 200) {
        return this.$message.error(result.msg)
      }
      this.projectList = result.data
    },
    async getTask(id) {
      const { data: result } = await this.$http.get('/task/' + id)
      if (result.status !== 200) {
        this.loading = false
        return this.$message.error(result.msg)
      }
      this.loading = false
      this.task = result.data
      this.oldCheck = result.data.check_status
      this.oldDev = result.data.dev_status
      this.task.note = result.data.note ? result.data.note : ' '
    },
    // 提交
    async handleSubmit () {
      this.$refs.task.validate(async (valid) => {
        const taskList = this.task.fileList.map(item => {
          return {
            url: item.url,
            name: item.name
          }
        })
        const date = new Date(this.task.estimated_date)
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        if (!valid) return
        let data = {
          dev_status: this.task.dev_status,
          project_id: this.task.project_id,
          task_name: this.task.task_name,
          task_user_id: this.task.task_user_id,
          estimated_date: `${year}-${month}-${day}`,
          is_check: this.task.is_check,
          check_status: this.task.check_status,
          file_url: taskList,
          desc: this.task.desc
        }
        if (this.editLog.text || this.editLog.picture) {
          const picList = this.editLog.picture.map(item => {
            return {
              url: item.url,
              name: item.name
            }
          })
          data.editLog = {
            text: this.editLog.text,
            user_id: this.userId,
            picture: picList
          }
        }
        const { data: result } = await this.$http.put('/task/' + this.id, { data: data })
        if (result.status !== 200) {
          return this.$message.error(result.msg)
        }
        this.$message.success('保存成功！')
        this.$router.push({ path: '/task-list' })
      })
    },
    // 返回
    back () {
      this.$router.push({ 'name': 'task-list' })
    },
    // 文件打开
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 移除文件
    async handleRemove(file, fileList) {
      this.task.fileList = fileList
    },
    beforeRemove(file, fileList) {
      var msg = '确定移除' + file.name + '？'
      return this.$confirm(msg)
    },
    // 上传失败
    handleError(err, file) {
      this.$message.warning(err)
    },
    // 文件上传成功
    handleSuccess(res, file, fileList) {
      file.url = res.data.url
      this.task.fileList = fileList
      this.$message.success(res.msg)
    },
    // 文件上传成功
    logSuccess(res, file, fileList) {
      file.url = res.data.url
      this.editLog.picture = fileList
      this.$message.success(res.msg)
    },
    // 移除文件
    async logRemove(file, fileList) {
      var url = file.response.data.downUrl
      await this.$http.post('/task-download-cancel', { url: url }, { type: 'json', responseType: 'blob' }).then(res => {
        if (res.status === 200) {
          this.editLog.picture = fileList
          return this.$message.success('移除成功')
        }
        return this.$message.error(res.msg)
      }).catch(() => {
        return this.$message.error('移除失败')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.title-name {
  margin-bottom: 20px;
}
.form-item {
  width:300px
}
.upload-demo {
  width: 300px;
}
</style>
